from django.views.generic import View
from .form import DatabaseForm, ProjectForm, EnvForm
from .models import DatabaseModel, ProjectModel, ProjectUserModel, EnvironmentModel
from auth_app.models import UserModel
from utils.messages import Form_Invalid, Json_Response
from utils.paginate import paginate
from utils.connections import mysql_connect
from utils.decorators import permission_verify
from utils.record import record
from copy import deepcopy


# Create your views here.


class DatabaseView(View):

    @permission_verify(20002)
    def insert(self, request):
        form = DatabaseForm.Insert(request)
        if form.is_valid():
            data = form.cleaned_data
            instance = DatabaseModel.objects.create(**data)
            record(request, 11, instance)
            return Json_Response(msg='创建成功')
        else:
            return Form_Invalid(form)

    @permission_verify(20002)
    def delete(self, request):
        form = DatabaseForm.Delete(request)
        if form.is_valid():
            for obj in DatabaseModel.objects.filter(id=form.cleaned_data['id']):
                obj_copy = deepcopy(obj)
                obj.delete()
                record(request, 12, obj_copy)
            return Json_Response(msg='删除成功')
        else:
            return Form_Invalid(form)

    @permission_verify(20002)
    def update(self, request):
        form = DatabaseForm.Update(request)
        if form.is_valid():
            data = form.cleaned_data
            id = data.pop('id')
            qs = DatabaseModel.objects.filter(id=id)
            qs.update(**data)
            for obj in qs:
                obj.save()
                record(request, 13, obj)
            return Json_Response(msg='修改成功')
        else:
            return Form_Invalid(form)

    @permission_verify(20001)
    def list(self, request):
        form = DatabaseForm.Select(request)
        if form.is_valid():
            result = []
            data = form.cleaned_data
            page, page_size = data['page'], data['page_size']
            t_qs = DatabaseModel.objects.filter()
            total = t_qs.count()
            qs = paginate(t_qs, page, page_size)
            for obj in qs.values(
                    'id', 'host', 'port', 'user', 'password', 'database', 'type', 'is_valid', 'desc',
            ):
                result.append(obj)
            return Json_Response(msg='查询成功', data={
                'page': page,
                'page_size': page_size,
                'total': total,
                'result': result
            })
        else:
            return Form_Invalid(form)

    def connect(self, request):
        form = DatabaseForm.Connect(request)
        if form.is_valid():
            for obj in DatabaseModel.objects.filter(id=form.cleaned_data['id']).values(
                    'host', 'port', 'user', 'password', 'database', 'type'):
                if obj['type'] == 'mysql':
                    print(obj, type(obj))
                    data = deepcopy(obj)
                    data.pop('type')
                    connect = mysql_connect(**data)
                    if connect:
                        connect.close()
                        return Json_Response(msg='连接成功')

            return Json_Response(code=201, err_msg='连接失败')
        else:
            return Form_Invalid(form)


class ProjectView(View):

    def _update_proj_user(self, proj_id, user_id_list: list):
        # 先清除所有对应关系，再添加新的对应关系
        ProjectUserModel.objects.filter(proj_id=proj_id).delete()
        for user_id in user_id_list:
            ProjectUserModel.objects.create(**{
                'proj': ProjectModel.objects.get(id=proj_id),
                'user': UserModel.objects.get(id=user_id)
            })

    def _get_proj_user(self, proj_id) -> [UserModel]:
        result = []
        for obj in ProjectUserModel.objects.filter(proj_id=proj_id):
            result.append(obj.user)
        return result

    @permission_verify(20004)
    def insert(self, request):
        form = ProjectForm.Insert(request)
        if form.is_valid():
            data = form.cleaned_data
            members = data.pop('proj_members')
            if not ProjectModel.objects.filter(proj_name=data['proj_name']):
                obj = ProjectModel.objects.create(**data)
                self._update_proj_user(obj.id, members)
                record(request, 11, obj)
            return Json_Response(msg='创建成功')
        else:
            return Form_Invalid(form)

    @permission_verify(20004)
    def update(self, request):
        form = ProjectForm.Update(request)
        if form.is_valid():
            data = form.cleaned_data
            id = data.pop('id')
            members = data.pop('proj_members')
            qs = ProjectModel.objects.filter(id=id)
            qs.update(**data)
            for obj in qs:
                obj.save()
                self._update_proj_user(obj.id, members)
                record(request, 13, obj)
            return Json_Response(msg='修改成功')
        else:
            return Form_Invalid(form)

    @permission_verify(20004)
    def delete(self, request):
        form = ProjectForm.Delete(request)
        if form.is_valid():
            id = form.cleaned_data['id']
            for obj in ProjectModel.objects.filter(id=id):
                obj_copy = deepcopy(obj)
                obj.delete()
                record(request, 12, obj_copy)
            return Json_Response(msg='删除成功')
        else:
            return Form_Invalid(form)

    @permission_verify(20003)
    def list(self, request):
        form = ProjectForm.List(request)
        if form.is_valid():
            result = []
            data = form.cleaned_data
            page, page_size = data['page'], data['page_size']
            qs = ProjectModel.objects.filter()
            total = qs.count()
            for obj in paginate(qs, page, page_size).values_list(
                    'id', 'proj_name', 'proj_desc', 'create_time', named=True):
                result.append({
                    'id': obj.id,
                    'proj_name': obj.proj_name,
                    'proj_desc': obj.proj_desc,
                    'create_time': obj.create_time,
                    'user': [{
                        'user_id': usr_obj.id,
                        'user_name': usr_obj.usr_name,
                    } for usr_obj in self._get_proj_user(obj.id)]
                })
            return Json_Response(msg='查询成功', data={
                'page': page,
                'page_size': page_size,
                'total': total,
                'result': result
            })
        else:
            return Form_Invalid(form)


class EnvView(View):
    @permission_verify(20006)
    def insert(self, request):
        form = EnvForm.Insert(request)
        if form.is_valid():
            data = form.cleaned_data
            if not EnvironmentModel.objects.filter(name=data['name']):
                obj = EnvironmentModel.objects.create(**data)
                record(request, 11, obj)
                return Json_Response(msg='新增成功')
            else:
                return Json_Response(code=201, err_msg='环境已存在')
        else:
            return Form_Invalid(form)

    @permission_verify(20006)
    def update(self, request):
        form = EnvForm.Update(request)
        if form.is_valid():
            data = form.cleaned_data
            id = data.pop('id')
            qs = EnvironmentModel.objects.filter(id=id)
            qs.update(**data)
            for obj in qs:
                obj.save()
                record(request, 13, obj)
            return Json_Response(msg='修改成功')
        else:
            return Form_Invalid(form)

    @permission_verify(20006)
    def delete(self, request):
        form = EnvForm.Delete(request)
        if form.is_valid():
            id = form.cleaned_data['id']
            for obj in EnvironmentModel.objects.filter(id=id):
                record(request, 12, obj)
                obj.delete()
            return Json_Response(msg='删除成功')
        else:
            return Form_Invalid(form)

    @permission_verify(20005)
    def list(self, request):
        form = EnvForm.List(request)
        if form.is_valid():
            result = []
            data = form.cleaned_data
            page, page_size = data.pop('page'), data.pop('page_size')
            qs = EnvironmentModel.objects.filter()
            total = qs.count()
            for obj in paginate(qs, page, page_size).values_list('id', 'name', 'host', 'port', named=True):
                result.append({
                    'id': obj.id,
                    'name': obj.name,
                    'host': obj.host,
                    'port': obj.port
                })

            return Json_Response(msg='查询成功', data={
                'page': page,
                'page_size': page_size,
                'total': total,
                'result': result
            })
        else:
            return Form_Invalid(form)
